<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function insert(intervals, newInterval) {
      let [a, b] = newInterval
      let flag = false
      let res = []
      for (let item of intervals) {
        let [c, d] = item
        if (c > b) {       // 当前左边比插入的右边大, 说明要在当前左边插入
          if (!flag) {
            res.push([a, b])
            flag = true
          }
          res.push(item)
        } else if (d < a) { // 当前右边比要插入的左边小, 说明要在当前的右边插入
          res.push(item)
        } else {              // 说明有相交
          a = Math.min(a, c)
          b = Math.max(b, d)
        }
      }
      if (!flag) res.push([a, b])

      return res
    };
    console.log(insert(intervals = [[1, 3], [6, 9]], newInterval = [2, 5]))
  </script>
</body>

</html>